﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class WorkDateController : Controller
    {
        /// <summary>
        /// 设置工作日
        /// </summary>
        /// <returns></returns>
        [Validate]
        public IActionResult Index()
        {
            DateTime now = DateExtensions.Now;
            int year = Request.Method.EqualsIgnoreCase("post") ? Request.Forms("DropDownList1").ToInt(now.Year) : now.Year;
            Business.WorkDate workDate = new Business.WorkDate();
            var list = workDate.GetYearList(year);
            StringBuilder options = new StringBuilder();
            for (int i = workDate.GetMinYear(); i <= now.Year + 1; i++)
            {
                options.Append("<option value='" + i + "'" + (i == year ? "selected='selected'" : "") + ">" + i + "</option>");
            }
            ViewData["year"] = year;
            ViewData["yearOptions"] = options.ToString();
            ViewData["queryString"] = Request.UrlQuery();
            return View(list);
        }
        /// <summary>
        /// 保存工作日设置
        /// </summary>
        /// <returns></returns>
        public string SaveWorkDate()
        {
            string year1 = Request.Forms("year1");
            string workdates = "," + Request.Forms("workdate") + ",";
            string daydate = Request.Forms("daydate");
            if (!year1.IsInt(out int year))
            {
                return "年份错误!";
            }
            List<Model.WorkDate> workDateList = new List<Model.WorkDate>();
            foreach (string date in daydate.Split(','))
            {
                if (!date.IsDateTime(out DateTime dt))
                {
                    continue;
                }
                if (dt.Year != year)
                {
                    continue;
                }
                int work = workdates.Contains("," + date + ",") ? 1 : 0;
                if (!workDateList.Exists(p => p.WorkDay == dt))
                {
                    workDateList.Add(new Model.WorkDate() { WorkDay = dt, IsWork = work });
                }
            }
            Business.Log.Add("设置了工作日", Newtonsoft.Json.JsonConvert.SerializeObject(workDateList), Business.Log.Type.系统管理);
            new Business.WorkDate().Add(workDateList.ToArray(), year);
            return "保存成功!";
        }
    }
}